/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable no-restricted-globals */
import { Modal, Form, Input } from 'antd';
import React, { useEffect } from 'react';
import { check } from '@/utils/patterns';
import { getLStorage } from '@/utils/utils';

const FormItem = Form.Item;

const SiteModal = props => {
  const { type, visible, form, onOk, onCancel, ...rest } = props;
  const { getFieldDecorator } = form;

  const title = type == 'add' ? '新增操作员' : '货架设置';

  const label = type == 'add' ? '手机号' : '每层放几个框';

  const placeholder = type == 'add' ? '请输入快递员手机号' : '请输入数量';

  const handleOk = () => {
    form.validateFields((err, value) => {
      if (err) return;
      onOk && onOk(value, type);
      form.resetFields();
    });
  };

  const handleCancel = () => {
    form.resetFields();
    onCancel();
  };

  const validator = (rule, value = '', callback) => {
    if (type == 'add') {
      const res = check('phone', value);
      if (res.code == 0) {
        callback();
      } else {
        callback(res.message);
      }
    } else if (isNaN(Number(value)) || value <= 0) {
      callback('请输入正确的数字');
    } else {
      callback();
    }
  };

  useEffect(
    () => {
      if (visible && type == 'edit') {
        const { frame_num } = getLStorage('frame_num') || {};
        if (frame_num) {
          form.setFieldsValue({
            input: frame_num,
          });
        }
      }
    },
    [visible],
  );

  return (
    <Modal visible={visible} title={title} onOk={handleOk} onCancel={handleCancel} {...rest}>
      <Form layout="inline">
        <FormItem label={label}>
          {getFieldDecorator('input', {
            rules: [
              {
                validator,
              },
            ],
            validateTrigger: 'onSubmit',
          })(<Input placeholder={placeholder} allowClear />)}
        </FormItem>
      </Form>
    </Modal>
  );
};

export default Form.create()(SiteModal);
